package com.hcinfos.gsoo.ui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.Area;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.LoginUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AddressUpdateActivity extends Activity implements OnClickListener {

	private LinearLayout area_ll;
	private ImageView back_iv;
	private Button save_bt;
	private EditText address_et;
	private TextView area_et;
	private EditText phone_et;
	private EditText name_et;
	private Dialog waitDialog;
	private RelativeLayout arrow_rl;
	private SharePreferenceUtil util;
	private ObjectMapper objectMapper;
	private String userName;
	private String phoneNum;
	private String address;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addressupdate);
		int width = getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		area_ll = (LinearLayout) findViewById(R.id.area_ll);
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		save_bt = (Button) findViewById(R.id.save_bt);
		arrow_rl = (RelativeLayout) findViewById(R.id.arrow_rl);
		arrow_rl.setOnClickListener(this);

		name_et = (EditText) findViewById(R.id.name_et);
		save_bt = (Button) findViewById(R.id.save_bt);
		address_et = (EditText) findViewById(R.id.address_et);
		area_et = (TextView) findViewById(R.id.area_et);
		area_et.setOnClickListener(this);
		phone_et = (EditText) findViewById(R.id.phone_et);
		save_bt.setOnClickListener(this);

		waitDialog = DialogUtil.createProgressDialog(this, "提示", "正在处理中...");
		util = new SharePreferenceUtil(this, "setting");
		objectMapper = new ObjectMapper();

	}

	private User user;

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putString("name", userName);
		outState.putString("phone", phoneNum);
		outState.putString("address", address);

		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		userName = savedInstanceState.getString("name");
		phoneNum = savedInstanceState.getString("phone");
		address = savedInstanceState.getString("address");
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onResume() {
		super.onResume();
		user = (User) util.loadObject("user");
		if (user != null && user.getTaName() != null) {
			name_et.setText(user.getTaName());
			phone_et.setText(user.getTaTelphone());
			address = user.getSendAddr1();
			if (address != null) {
				String[] str = address.split(",");
				if (str.length > 1) {
					if (resultArea != null) {
						area_et.setText(resultArea);
					} else {
						area_et.setText(str[0]);
					}

					address_et.setText(str[1]);
				} else {
					address_et.setText(address);
				}
			}
		}
	}

	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.area_et:
			userName = name_et.getText().toString();
			phoneNum = phone_et.getText().toString();
			address = address_et.getText().toString();
			intent = new Intent(this, MoreAreaActivity.class);
			startActivityForResult(intent, 0);
			break;
		case R.id.back_iv:
			finish();
			break;
		case R.id.save_bt:
			waitDialog.show();
			modifyUser();
			break;
		}
	}

	private String resultArea = null;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			Area area = (Area) data.getSerializableExtra("area");
			if (area != null) {
				LogUtil.d("wxf", "areaName=" + area.getAreaName());
				area_et.setText(area.getAreaName());
				resultArea = area.getAreaName();
				if (userName != null)
					name_et.setText(userName);
				if (phoneNum != null)
					phone_et.setText(phoneNum);
				if (address != null)
					address_et.setText(address);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public boolean isPhoneNumberValid(String phoneNumber) {
		boolean isValid = false;
		String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}d{1}-?d{8}$)|"
				+ "(^0[3-9] {1}d{2}-?d{7,8}$)|"
				+ "(^0[1,2]{1}d{1}-?d{8}-(d{1,4})$)|"
				+ "(^0[3-9]{1}d{2}-? d{7,8}-(d{1,4})$))";
		CharSequence inputStr = phoneNumber;
		Pattern pattern = Pattern.compile(expression);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValid = true;
		}
		return isValid;
	}

	private void modifyUser() {

		final String area = area_et.getText().toString();
		final String address = address_et.getText().toString();
		final String tel = phone_et.getText().toString();
		final String name = name_et.getText().toString();
		if (tel.length() == 0 || address.length() == 0 || name.length() == 0
				|| area.length() == 0) {
			waitDialog.dismiss();
			Toast.makeText(this, "请填写全部的内容", 500).show();
			return;
		}
		if (!isPhoneNumberValid(tel)) {

			Toast.makeText(this, "手机格式不对！", 500).show();

			return;
		}

		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("_addr1", area + "," + address);
		params.addBodyParameter("_ta_telphone", tel);
		params.addBodyParameter("_ta_name", name);
		http.send(HttpRequest.HttpMethod.POST,
				Urls.gdTakeAwayOrderExt_modifyUserTaAddrs, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", responseInfo.result);
						try {

							JSONObject obj = new JSONObject(responseInfo.result);
							int state = obj.getInt("state");
							if (state == 200) {
								user.setSendAddr1(area + address);
								user.setTaName(name);
								user.setTaTelphone(tel);
								handler.sendEmptyMessage(UPDATE_SUCCESS);
							} else if (state == 198) {
								handler.sendEmptyMessage(LOGIN);
							} else {

								handler.sendEmptyMessage(UPDATE_FAIL);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(UPDATE_FAIL);

						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(UPDATE_FAIL);

					}

				});
	}

	public final int UPDATE_SUCCESS = 0x2210;
	public final int UPDATE_FAIL = UPDATE_SUCCESS + 1;
	public final int LOGIN = UPDATE_SUCCESS + 2;
	public final int LOGIN_SUCCESS = UPDATE_SUCCESS + 3;
	public final int LOGIN_FAIL = UPDATE_SUCCESS + 4;

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case UPDATE_SUCCESS:
				util.saveObject(user, "user");
				// isLoginSuccess(AddressUpdateActivity.this);
				Toast.makeText(AddressUpdateActivity.this, "修改成功!", 500).show();
				waitDialog.dismiss();
				finish();
				break;
			case UPDATE_FAIL:
				waitDialog.dismiss();
				Toast.makeText(AddressUpdateActivity.this, "提交失败!", 500).show();
				break;
			case LOGIN:
				LoginUtil.isLoginSuccess(AddressUpdateActivity.this, handler);
				break;
			case LoginUtil.LOGIN_FAIL:
				waitDialog.dismiss();
				Toast.makeText(AddressUpdateActivity.this, "提交失败!", 500).show();
				break;
			case LoginUtil.LOGIN_SUCCESS:
				modifyUser();
				break;
			case LOGIN_SUCCESS:

				break;
			case LOGIN_FAIL:
				waitDialog.dismiss();
				Toast.makeText(AddressUpdateActivity.this, "提交失败!", 500).show();
				break;
			}

		};
	};

	public void isLoginSuccess(Context context) {

		User user = (User) util.loadObject("user");
		if (user == null)
			handler.sendEmptyMessage(LoginUtil.LOGIN_FAIL);
		String loginName = user.getEmail() == null ? user.getGgnumber() : user
				.getEmail();
		HttpUtils http = UtilHttp.getHttpUtils(context);
		RequestParams params = new RequestParams();
		params.addBodyParameter("user.email", loginName);
		params.addBodyParameter("user.password", user.getPassword());
		http.send(HttpRequest.HttpMethod.POST, Urls.NEW_USER_LOGIN, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						Log.e("wxf", arg0.toString());
						handler.sendEmptyMessage(LOGIN_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> text) {

						String result = text.result;
						Log.d("wxf", "login=" + text.result);
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								User user = objectMapper.readValue(
										obj.getString("data"),
										new TypeReference<User>() {
										});

								handler.sendEmptyMessage(LOGIN_SUCCESS);
							} else {
								handler.sendEmptyMessage(LOGIN_FAIL);

							}
						} catch (Exception e) {
							handler.sendEmptyMessage(LOGIN_FAIL);
							Log.e("wxf", e.toString());
						}

					}

				});

	}
}
